﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CIT.WMS.houseWork.Helper;

namespace CIT.WMS.output
{
    public partial class FrmMateJJ : Form
    {
        bool flag = false;
        bool result = false;
        public FrmMateJJ()
        {
            InitializeComponent();
            lbl_PO.Text = string.Empty;
            lbl_msg.Text = string.Empty;
            lbl_LastQty.Text = string.Empty;
            lbl_ActQty.Text = string.Empty;
        }

        private void txt_SerialNumber_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (txt_SerialNumber.Text.Trim() == string.Empty)
                {
                    ShowInfo("输入不能为空", false);
                    return;
                }
                //判断物料条码还是单据号

                string strSql = string.Format(@"SELECT TOP 1 B.SfcNo, A.S_Doc_NO,B.S_Doc_Type,A.Receive_Flag,C.Prepare_Flag,A.QTY,a.MaterialCode,WEBAPI_URL,WEBAPI,B.PLCode 
FROM dbo.T_Bllb_StorageDocDetail_tbsdd A LEFT JOIN 
dbo.T_Bllb_StorageDoc_tbsd B ON A.S_Doc_NO=B.S_Doc_NO
LEFT JOIN dbo.T_Bllb_DocType_tbdt C ON C.TYPE_CODE=B.S_Doc_Type
 WHERE SerialNumber='{0}' ORDER BY A.Create_Time DESC", txt_SerialNumber.Text.Trim());
                DataTable dt_stock = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                string doc_no = string.Empty;
                #region 物料
                //判断物料是否处于备料状态
                if (dt_stock.Rows.Count > 0)
                {
                    string S_Doc_Type = SqlInput.ChangeNullToString(dt_stock.Rows[0]["S_Doc_Type"]);//单据是否为发料单
                    if (S_Doc_Type != "7")
                    {
                        ShowInfo("物料不是发料状态", false);
                        return;
                    }
                    string Receive_Flag = SqlInput.ChangeNullToString(dt_stock.Rows[0]["Receive_Flag"]);//物料是否已交接
                    if (Receive_Flag == "Y")
                    {
                        ShowInfo("物料已交接", false);
                        return;
                    }
                    doc_no = SqlInput.ChangeNullToString(dt_stock.Rows[0]["S_Doc_NO"]);
                    //修改物料在备料单中的状态为已交接
                    strSql = string.Format(@" UPDATE dbo.T_Bllb_StorageDocDetail_tbsdd SET Receive_Flag='Y' WHERE S_Doc_NO='{0}' AND SerialNumber='{1}' ", doc_no, txt_SerialNumber.Text.Trim());
                    strSql += string.Format(@" UPDATE dbo.T_Bllb_StockInfo_tbsi SET Lock_Flag='7' WHERE SerialNumber='{0}' ", txt_SerialNumber.Text.Trim());
                    strSql += string.Format(@" INSERT INTO T_Bllb_MaterialLog_tbml(SerialNumber,CreateTime,OperateType,MaterialCode,QTY,Creator,Memo,SfcNo,PLCode)
VALUES('{0}',GETDATE(),'{1}','{2}','{3}','{4}','{5}','{6}','{7}') ", txt_SerialNumber.Text.Trim(), "交接", SqlInput.ChangeNullToString(dt_stock.Rows[0]["MaterialCode"]), SqlInput.ChangeNullToInt(dt_stock.Rows[0]["QTY"], 0), Utils.uContext.UserNamek__BackingField, "", "", "");

                    #region SMT段数据处理
                    string sql = string.Format(@"SELECT TOP 1 B.WoCode,B.SfcNo,'' slot,B.PLCode,A.MaterialCode,A.QTY FROM dbo.T_Bllb_StorageDocDetail_tbsdd A 
LEFT JOIN dbo.T_Bllb_StorageDoc_tbsd B ON A.S_Doc_NO=B.S_Doc_NO
LEFT JOIN dbo.SfcDatProduct C ON B.SfcNo=C.SfcNo
WHERE A.SerialNumber='{0}' AND A.S_Doc_NO='{1}' ORDER BY A.Create_Time DESC", txt_SerialNumber.Text.Trim(), doc_no);
                    DataTable dt_SMT = Utils.NMS.QueryDataTable(Utils.uContext, sql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    if (dt_SMT.Rows.Count > 0)
                    {                       
                        string wocode = SqlInput.ChangeNullToString(dt_SMT.Rows[0]["WoCode"]);//工单
                        string line = SqlInput.ChangeNullToString(dt_SMT.Rows[0]["PLCode"]);//线别
                        string sfcno = SqlInput.ChangeNullToString(dt_SMT.Rows[0]["SfcNo"]);//制令单
                        string MaterialCode = SqlInput.ChangeNullToString(dt_SMT.Rows[0]["MaterialCode"]);//料号
                        string qty = SqlInput.ChangeNullToString(dt_SMT.Rows[0]["QTY"]);//数量
                        string slot = SqlInput.ChangeNullToString(dt_SMT.Rows[0]["slot"]);//slot
                        if (line.ToUpper().StartsWith("SMT"))
                        {
                            #region MSD物料信息获取
                            string IsMSD = string.Empty;
                            int ExposureTime = 0;//允许暴露时间
                            int TotalExposedTime = 0;//总暴露时间
                            string sqlmsd = string.Format(@"	SELECT  
		b.IsMSD AS MSD ,
		isnull(c.ExposeTime,0)*60 AS ExposureTime,
		(isnull(e.Expose_Time_Length,0)+isnull(e.LifeCycle,0)) as TotalExposedTime
FROM    dbo.T_Bllb_StockInfo_tbsi AS a
        LEFT JOIN dbo.MdcdatMaterial AS b ON a.MaterialCode = b.MaterialCode
        LEFT JOIN dbo.T_Bllb_SecondClass_tbsc AS c ON c.Class = b.SecondMaterialClass
        LEFT JOIN dbo.T_Bllb_MSDMain_tbmm AS d ON d.SerialNumber = a.SerialNumber
		LEFT JOIN dbo.T_Bllb_MSDResult_tbmr AS e ON e.SerialNumber=d.SerialNumber
		WHERE 1=1 AND a.SerialNumber='{0}'", txt_SerialNumber.Text.Trim());
                            DataTable dt_MSD = Utils.NMS.QueryDataTable(Utils.uContext, sqlmsd, new CIT.WMS.MESWcf.CmdParameter[0]);
                            if (dt_MSD.Rows.Count > 0)
                            {
                                IsMSD = SqlInput.ChangeNullToString(dt_MSD.Rows[0]["MSD"]);//是MSD物料
                                if (IsMSD == "0")//在MdcdatMaterial表中是MSD
                                {
                                    IsMSD = "1";//在PUB_UniqueCodeInLine表中1是MSD
                                    ExposureTime = SqlInput.ChangeNullToInt(dt_MSD.Rows[0]["ExposureTime"], 0);
                                    TotalExposedTime = SqlInput.ChangeNullToInt(dt_MSD.Rows[0]["TotalExposedTime"], 0);
                                }
                            }
                            #endregion
                            //每出库一盘，往PVS中写一条数据
                            //写入PVS表中，当前不做接收的动作直接发送过去
                            strSql += string.Format(@" insert into JIT_BufferMaterial (CallOrderNo,LineName,WorkOrderNo,MOrderNo,UniqueCode,MatrCode,Qty,Position,SysOwner,CreateTime)
                    values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}',getdate()) ", wocode, line, wocode, sfcno, txt_SerialNumber.Text.Trim(), MaterialCode, qty, slot, Utils.uContext.UserNamek__BackingField);
                            //PVS防错使用
                            if (IsMSD == "1")
                            {
                                strSql += @" if not exists(select * from PUB_UniqueCodeInLine where uniquecode='" + txt_SerialNumber.Text.Trim() + @"')begin insert into PUB_UniqueCodeInLine(workorderno,morderno,uniquecode,matrcode,qty,Supplier,lotno,MSD,ExposureTime,TotalExposedTime)
                                    values('" + wocode + "','" + sfcno + "','" + txt_SerialNumber.Text.Trim() + "','" + MaterialCode + "','" + qty + "','" + "','" + "'," + IsMSD + "," + ExposureTime + "," + TotalExposedTime + @") end 
                                    update PUB_UniqueCodeInLine set WorkOrderNo='" + wocode + "',morderno='" + sfcno + "',matrcode='" + MaterialCode + "',qty='" + qty + "',Supplier='',lotno='',MSD=" + IsMSD + ",ExposureTime=" + ExposureTime + ",TotalExposedTime=" + TotalExposedTime + " where  UniqueCode='" + txt_SerialNumber.Text.Trim() + "'";
                            }
                            else
                            {
                                strSql += @" if not exists(select * from PUB_UniqueCodeInLine where uniquecode='" + txt_SerialNumber.Text.Trim() + @"')begin insert into PUB_UniqueCodeInLine(workorderno,morderno,uniquecode,matrcode,qty,Supplier,lotno)
                                    values('" + wocode + "','" + sfcno + "','" + txt_SerialNumber.Text.Trim() + "','" + MaterialCode + "','" + qty + "','" + "','" + @"') end 
                                    update PUB_UniqueCodeInLine set WorkOrderNo='" + wocode + "',morderno='" + sfcno + "',matrcode='" + MaterialCode + "',qty='" + qty + "',Supplier='',lotno='' where  UniqueCode='" + txt_SerialNumber.Text.Trim() + "'";
                            }                        
                        }  
                    }
                    #endregion
                    Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                    strSql = string.Empty;
                    string strQuerySql = string.Format(@"SELECT ISNULL(SUM(CASE WHEN Receive_Flag='Y' THEN 1 ELSE 0 END),0) Receive_Qty,ISNULL(SUM(CASE WHEN Receive_Flag='N' THEN 1 ELSE 0 END),0) NOT_Receive_Qty FROM dbo.T_Bllb_StorageDocDetail_tbsdd WHERE S_Doc_NO='{0}'", doc_no);
                    DataTable dt_Receive_Flag = Utils.NMS.QueryDataTable(Utils.uContext, strQuerySql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    if (dt_Receive_Flag.Rows.Count > 0)//交接结束
                    {
                        if (dt_Receive_Flag.Rows[0]["NOT_Receive_Qty"].ToString() == "0" & dt_Receive_Flag.Rows[0]["Receive_Qty"].ToString() != "0")
                        {
                            strSql = string.Format(@" UPDATE dbo.SfcDatProduct SET Status=8 WHERE SfcNo='{0}' AND Status=1", SqlInput.ChangeNullToString(dt_stock.Rows[0]["SfcNo"]));
                            Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                        }
                    }
                    lbl_LastQty.Text = dt_Receive_Flag.Rows[0]["NOT_Receive_Qty"].ToString();
                    lbl_ActQty.Text = dt_Receive_Flag.Rows[0]["Receive_Qty"].ToString();
                    lbl_PO.Text = doc_no;
                    ShowInfo("物料交接成功", true);
                    return;
                }

                #endregion
                else
                {
                    ShowInfo("输入信息无效", false);
                    return;
                    #region 单据
                    strSql = string.Format(@" SELECT ISNULL(SUM(CASE WHEN a.Receive_Flag='Y' THEN 1 ELSE 0 END),0) RECEIVE_QTY,COUNT(1) SUM_QTY,B.SfcNo  ,C.Prepare_Flag,b.Close_Flag,C.WEBAPI_URL,C.WEBAPI,A.S_Doc_NO 
FROM dbo.T_Bllb_StorageDocDetail_tbsdd A LEFT JOIN dbo.T_Bllb_StorageDoc_tbsd B ON A.S_Doc_NO=B.S_Doc_NO
LEFT JOIN dbo.T_Bllb_DocType_tbdt C ON B.S_Doc_Type=C.TYPE_CODE
 WHERE A.S_Doc_NO='{0}' GROUP BY C.Prepare_Flag,b.Close_Flag,C.WEBAPI_URL,C.WEBAPI,A.S_Doc_NO,B.SfcNo ", txt_SerialNumber.Text.Trim());
                    DataTable dt_qty = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    if (dt_qty.Rows.Count > 0)
                    {
                        doc_no = txt_SerialNumber.Text.Trim();
                        string Prepare_Flag = SqlInput.ChangeNullToString(dt_qty.Rows[0]["Prepare_Flag"]);//单据是否为备料单类型
                        if (Prepare_Flag == "N")
                        {
                            ShowInfo("物料最后所属的单据不是备料单", false);
                            return;
                        }
                        string Close_Flag = SqlInput.ChangeNullToString(dt_qty.Rows[0]["Close_Flag"]);//单据是否为备料单类型
                        if (Close_Flag == "Y")
                        {
                            ShowInfo("备料单已关闭", false);
                            return;
                        }
                        string strQuerySql = string.Format(@"SELECT COUNT(1) FROM dbo.T_Bllb_StorageDocDetail_tbsdd WHERE S_Doc_NO='{0}' AND Receive_Flag='Y'", doc_no);
                        DataTable dt_Receive_Flag = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                        strSql = string.Empty;
                        if (dt_Receive_Flag.Rows[0][0].ToString() != "0")//交接结束
                        {
                            strSql += string.Format(@"UPDATE dbo.SfcDatProduct SET Status=8 WHERE SfcNo='{0}' AND Status=1", SqlInput.ChangeNullToString(dt_qty.Rows[0]["SfcNo"]));
                        }

                        //修改物料在备料单中的状态为已交接                       
                        strSql += string.Format(@" UPDATE dbo.T_Bllb_StorageDocDetail_tbsdd SET Receive_Flag='Y' WHERE S_Doc_NO='{0}'", doc_no);
                        //关闭单据
                        strSql += string.Format(@" UPDATE dbo.T_Bllb_StorageDoc_tbsd SET Close_Flag='Y' WHERE S_Doc_NO='{0}'", doc_no);
                        //物料操作日志
                        strSql += string.Format(@" INSERT INTO T_Bllb_MaterialLog_tbml(SerialNumber,CreateTime,OperateType,MaterialCode,QTY,Creator,Memo,SfcNo,PLCode)
 SELECT SerialNumber,GETDATE(),'{1}',MaterialCode,QTY,'{2}','{3}','','' FROM dbo.T_Bllb_StorageDocDetail_tbsdd WHERE S_Doc_NO='{0}'", txt_SerialNumber.Text.Trim(), "交接", Utils.uContext.UserIDk__BackingField, "", "", "");
                        
                        strSql += string.Format(@" UPDATE dbo.T_Bllb_StockInfo_tbsi SET Lock_Flag='7' WHERE SerialNumber IN (SELECT SerialNumber FROM T_Bllb_StorageDocDetail_tbsdd WHERE S_Doc_NO='{0}') ", doc_no);
                        #region SMT段数据处理
                        string sql = string.Format(@"SELECT top 1 B.WoCode,B.SfcNo,'' slot,B.PLCode,A.MaterialCode,A.QTY FROM dbo.T_Bllb_StorageDocDetail_tbsdd A 
LEFT JOIN dbo.T_Bllb_StorageDoc_tbsd B ON A.S_Doc_NO=B.S_Doc_NO
LEFT JOIN dbo.SfcDatProduct C ON B.SfcNo=C.SfcNo
WHERE A.S_Doc_NO='{0}' AND A.Receive_Flag='N'  ORDER BY A.Create_Time DESC", doc_no);
                        DataTable dt_SMT = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                        if (dt_SMT.Rows.Count > 0)
                        {
                            string line = SqlInput.ChangeNullToString(dt_SMT.Rows[0]["PLCode"]);//线别
                            if (line.ToUpper().StartsWith("SMT"))
                            {  //写入PVS表中，当前不做接收的动作直接发送过去
                                strSql += string.Format(@" insert into JIT_BufferMaterial (CallOrderNo,LineName,WorkOrderNo,MOrderNo,UniqueCode,MatrCode,Qty,Position,SysOwner,CreateTime)
SELECT B.WoCode,B.Line, B.WoCode,B.SfcNo,A.SerialNumber,B.MaterialCode, A.QTY,B.slot,'{1}',GETDATE() FROM dbo.T_Bllb_StorageDocDetail_tbsdd A 
INNER JOIN dbo.T_Bllb_StorageDocSMT_tbds B ON A.TBDS_ID=B.TBDS_ID 
WHERE  A.S_Doc_NO='{0}' AND A.Receive_Flag='N'", doc_no, Utils.uContext.UserNamek__BackingField);
                                //PVS防错使用
                                strSql += string.Format(@" DELETE FROM PUB_UniqueCodeInLine WHERE uniquecode IN 
(SELECT A.SerialNumber FROM dbo.T_Bllb_StorageDocDetail_tbsdd A 
INNER JOIN dbo.T_Bllb_StorageDocSMT_tbds B ON A.TBDS_ID=B.TBDS_ID WHERE  A.S_Doc_NO='{0}' AND A.Receive_Flag='N')", doc_no);
                                strSql += string.Format(@" insert into PUB_UniqueCodeInLine(workorderno,morderno,uniquecode,matrcode,qty,Supplier,lotno)
SELECT  B.WoCode,B.SfcNo,A.SerialNumber,B.MaterialCode, A.QTY,'','' FROM dbo.T_Bllb_StorageDocDetail_tbsdd A 
LEFT JOIN dbo.T_Bllb_StorageDocSMT_tbds B ON A.TBDS_ID=B.TBDS_ID WHERE  A.S_Doc_NO='{0}' AND A.Receive_Flag='N'", doc_no);

                            }

                        }
                        //string strQuerySql = string.Format(@"SELECT COUNT(1) FROM dbo.T_Bllb_StorageDocDetail_tbsdd WHERE S_Doc_NO='{0}' AND Receive_Flag='Y'", doc_no);
                        //DataTable dt_Receive_Flag = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);

                        Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);

                        strSql = string.Format(@"SELECT SUM(CASE WHEN Receive_Flag='Y' THEN 1 ELSE 0 END) Receive_Qty,SUM(CASE WHEN Receive_Flag='N' THEN 1 ELSE 0 END) NOT_Receive_Qty FROM dbo.T_Bllb_StorageDocDetail_tbsdd WHERE S_Doc_NO='{0}'", doc_no);
                        DataTable dt_Receive_Flag2 = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                        if (dt_Receive_Flag2.Rows.Count > 0)//交接结束
                        {
                            lbl_LastQty.Text = dt_Receive_Flag2.Rows[0]["NOT_Receive_Qty"].ToString();
                            lbl_ActQty.Text = dt_Receive_Flag2.Rows[0]["Receive_Qty"].ToString();
                            lbl_PO.Text = doc_no;

                        }
                        #endregion
                        ShowInfo("单据" + doc_no + "交接成功", true);
                        return;
                    }
                    else
                    {
                   
                    }

                    #endregion                

                }
         
            }
        }

        private void ShowInfo(string msg, bool isOK)
        {
            lbl_msg.Text = msg;
            lbl_msg.ForeColor = isOK == true ? Color.Green : Color.Red;
            txt_SerialNumber.SelectAll();
        }
    }
}